import { FC, useEffect, useCallback, Key } from 'react';
import { Col, Row, Space, Tooltip } from 'antd';
import type { FormInstance, FormItemProps } from 'antd/lib/form';
import classNames from 'classnames';
import { observer, useLocalStore } from 'mobx-react';
import { toJS } from 'mobx';

import Icons from '@components/Icons';
import Button from '@components/Button';
import Form, { Item as FormItem } from '@components/Form';
import { formatParams } from '@/utils/util';

import styles from './index.module.less';

export type CollapseQueryBarProps = {
  /** 表单实例 */
  form: FormInstance;

  /** 表单配置 */
  queryFromItems: FormItemProps[];

  /** 查询方法 */
  handleSearch: (params: any) => void;

  /** 加载状态 */
  loading?: boolean;

  /**
   * 每行列数
   * @default 3
   */
  columns?: 1 | 2 | 3 | 4;

  /**
   * 是否默认展开查询条
   * @default false
   */
  defaultExpand?: boolean;

  /**
   * 图标代替文字
   * @default false
   * @example'一般用于小布局'
   */
  isIconBtn?: boolean;

  /**
   * 查询条件处理
   * @example '一般用于处理请求前的时间参数'
   */
  queryFormat?: any;

  /** 查询表单初始化值 */
  initialValues?: { [key: string]: any };
};

export type CollapseQueryBarStore = {
  /** 展开/收起 */
  expand: boolean;

  /** 表单项大小 */
  fromItemColSpan: 24 | 12 | 8 | 6;

  /** 表单项集合 */
  fromItems: FormItemProps[];
};

/** 获取表单实际的列 */
const getFromItems = (items: FormItemProps[]): FormItemProps[] => {
  return items.filter((item: FormItemProps) => !item.hidden);
};

const CollapseQueryBar: FC<CollapseQueryBarProps> = ({
  form,
  queryFromItems,
  columns = 3,
  loading = false,
  defaultExpand = false,
  handleSearch,
  isIconBtn = false,
  queryFormat,
  initialValues = {}
}) => {
  const store: CollapseQueryBarStore = useLocalStore(() => ({
    expand: defaultExpand,
    fromItemColSpan: 8,
    fromItems: []
  }));

  useEffect(() => {
    // 初始化设置列宽
    store.fromItemColSpan = (24 / columns) as 24 | 12 | 8 | 6;

    // 获取表单列
    store.fromItems = getFromItems(queryFromItems);
  }, [columns, queryFromItems]);

  /** 表单重置 */
  const handleFormReset = useCallback(() => {
    form?.resetFields();
  }, [form]);

  return (
    <Form
      loading={loading}
      form={form}
      onFinish={params => {
        const newParams = formatParams(params, queryFormat);
        handleSearch(newParams);
      }}
      initialValues={initialValues}
    >
      <Row gutter={12}>
        {/* 查询表单 */}
        <Col span={18}>
          <Row gutter={24}>
            {toJS(store.fromItems).map((item: FormItemProps, index: number) => (
              <Col span={store.fromItemColSpan} key={item.name as Key}>
                <FormItem {...item} hidden={!store.expand && index > columns - 1} />
              </Col>
            ))}
          </Row>
        </Col>
        {/* 查询按钮 */}
        <Col span={6} className={classNames(styles.rbCollapseQueryBarBtnCol)}>
          {store.fromItems.length > columns && (
            <Tooltip
              title={
                isIconBtn && store.expand ? '收起' : isIconBtn && !store.expand ? '更多' : undefined
              }
            >
              <Button
                onClick={() => (store.expand = !store.expand)}
                style={{ marginRight: 8 }}
                shape={isIconBtn ? 'circle' : undefined}
              >
                <Space>
                  <Icons type={store.expand ? 'UpOutlined' : 'DownOutlined'} />
                  {!isIconBtn && <span>{store.expand ? '收起' : '更多'}</span>}
                </Space>
              </Button>
            </Tooltip>
          )}
          <Tooltip title={isIconBtn ? '重置' : undefined}>
            <Button
              style={{ marginRight: 8 }}
              onClick={handleFormReset}
              shape={isIconBtn ? 'circle' : undefined}
            >
              {isIconBtn ? <Icons type="RedoOutlined" /> : '重置'}
            </Button>
          </Tooltip>
          <Tooltip title={isIconBtn ? '查询' : undefined}>
            <Button type="primary" htmlType="submit" shape={isIconBtn ? 'circle' : undefined}>
              {isIconBtn ? <Icons type="SearchOutlined" /> : '查询'}
            </Button>
          </Tooltip>
        </Col>
      </Row>
    </Form>
  );
};

export default observer(CollapseQueryBar);
